package com.lb.kafka;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.Properties;

public class KafkaConsumerExample {

    private static final String TOPIC = "test-topic";  // Kafka 主题

    public static void main(String[] args) {
        // 设置 Kafka 消费者的配置
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.31.201:9092");  // Kafka 服务地址
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-group");  // 消费者组 ID
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());  // 键的反序列化方式
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());  // 值的反序列化方式

        // 创建 Kafka 消费者
        Consumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        // 订阅 Kafka 主题
        consumer.subscribe(Collections.singletonList(TOPIC));

        // 不断消费消息
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(1000);// 每 1000 毫秒拉取一次消息
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("Consumed message: " + record.value() + " from partition " + record.partition());
            }
        }
    }
}
